package top.fengyulou.qmy.controller;

import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.fengyulou.common.Jr;
import top.fengyulou.qmy.entity.ProjectForm;
import top.fengyulou.qmy.service.ProjectService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class ProjectController {

    @Resource
    private ProjectService projectService;

    @GetMapping("/project/list")
    public String projectList(HttpServletRequest request, ProjectForm form) {
        //查询数据
        PageInfo<ProjectForm> pageInfo = projectService.getPageList(form);
        //将数据放入请求域
        request.setAttribute("page", pageInfo);
        request.setAttribute("form", form);
        return "project-list";
    }

    @GetMapping("/project/add")
    public String projectAdd() {
        return "project-save";
    }

    /**
     * 添加操作
     */
    @PostMapping("/project/ajax/add")
    @ResponseBody
    public Jr ajaxAdd(ProjectForm form) {
        //验证数据
        Jr jr = checkForm(form);
        if (!jr.isStatus()) {
            return jr;
        }
        //添加操作
        projectService.insert(form);
        return Jr.yes();
    }

    /**
     * 检查数据
     */
    private Jr checkForm(ProjectForm form) {
        if (StringUtils.isBlank(form.getName())) {
            return Jr.no("未输入项目名称");
        }
        return Jr.yes();
    }

    @GetMapping("/project/update/{id}")
    public String projectUpdate(HttpServletRequest request, @PathVariable("id") Long id) {
        ProjectForm project = projectService.getById(id);
        request.setAttribute("form", project);
        return "project-save";
    }

    /**
     * 修改操作
     */
    @PostMapping("/project/ajax/update")
    @ResponseBody
    public Jr ajaxUpdate(ProjectForm form) {
        //检查数据
        Jr jr = checkForm(form);
        if (!jr.isStatus()) {
            return jr;
        }
        //修改操作
        projectService.update(form);
        return Jr.yes();
    }

    /**
     * 删除操作
     */
    @PostMapping("/project/ajax/delete")
    @ResponseBody
    public Jr ajaxDelete(@RequestParam("id") Long id) {
        //修改操作
        projectService.delete(id);
        return Jr.yes();
    }
}
